import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
    Row, Col, Card, Form, Input,
    Select, Icon, Button, Dropdown, Menu, Popconfirm,
    InputNumber, DatePicker, Modal, message, Checkbox,
    Badge, Divider, Tag, Table, Radio
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'dva/router';
import styles from './ProductCatalog.less';
import TextArea from 'antd/lib/input/TextArea';
import querystring from 'querystring';
const FormItem = Form.Item;
const Option = Select.Option;
const { MonthPicker, RangePicker } = DatePicker;
const monthFormat = 'YYYY-MM-DD';
/*
  产品管理的产品添加
*/

const EditableCell = ({ editable, value, onChange }) => (
    <div>
        {editable
            ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} />
            : value
        }
    </div>
);

@connect(({ product }) => ({
    product,
    // loading: loading.models.rule,
}))
@Form.create()
export default class ProductAdd extends PureComponent {
    state = {
        productVariety: '',
        retailData: [],
        selectTimeType: false,
        endOpen: false,
        isEndTime: false,
        initRetailCount: 0,
        assetTypeValue: '',
        isEdit: true,
    };
    componentDidMount() {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        dispatch({
            type: 'product/queryProductDetails',
            payload: {
                id: params.id,
            },
        });
        this.setState({
            type: params.type,
            productId: params.id,
        });
    }

    handleChangeProductVariety = (value) => {
        this.setState({
            productVariety: value
        })
    }

    handleAssetsTypeVariety = (value) => {
        this.setState({
            assetTypeValue: value
        })
    }

    onRetailData = () => {
        if (this.state.initRetailCount == 0) {
            for (let i = 1; i < 4; i++) {
                this.state.retailData.push({
                    key: i,
                    nper: `${(4 * i) * 3}`,
                    price: ` 0`,
                    type: 0,
                    isPreset: i <= 3,
                });
            }
            this.state.initRetailCount = 1
        }
    }
    constructor(props) {
        super(props);

        this.renderDelete = (record) => {
            return (
                <span>
                    <a onClick={() => this.editRetail(record.key)}>编辑</a>
                    {!record.isPreset && <Popconfirm title="确定要删除吗?" onConfirm={() => this.deleteRetail(record.key)}>
                        <a style={{ marginLeft: 10 }}>删除</a>
                    </Popconfirm>}
                </span>
            );
        }
        this.columnsRetail = [{
            title: '期数',
            dataIndex: 'nper',
            key: 'nper',
            align: 'center',
            render: (text, record) => this.renderColumnsRetail(text, record, 'nper'),
        }, {
            title: '费率',
            dataIndex: 'price',
            key: 'price',
            align: 'center',
            render: (text, record) => this.renderColumnsRetail(text, record, 'price'),
        }, {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            render: (text, record) => {
                const { editable } = record;
                return (
                    <div className="editable-row-operations">
                        {
                            editable ?
                                <span>
                                    <a onClick={() => this.saveRetail(record.key)}>保存</a>
                                    <Popconfirm title="确定要取消吗?" onConfirm={() => this.cancelRetail(record.key)}>
                                        <a style={{ marginLeft: 10 }}>取消</a>
                                    </Popconfirm>
                                </span>
                                :
                                this.renderDelete(record)
                        }
                    </div>
                );
            },
        }];
        this.renderChannelDelete = (record) => {
            return (
                <span>
                    <a onClick={() => this.editChannel(record.key)}>编辑</a>
                    {!record.isPreset && <Popconfirm title="确定要删除吗?" onConfirm={() => this.deleteChannel(record.key)}>
                        <a style={{ marginLeft: 10 }}>删除</a>
                    </Popconfirm>}
                </span>
            );
        }
        this.cacheDataRetail = this.state.retailData.map(item => ({ ...item }));
    }

    renderColumnsRetail(text, record, column) {
        return (
            record.isPreset && column == 'nper' ?
                text
                :
                <EditableCell
                    editable={record.editable}
                    value={text}
                    onChange={value => this.handleChangeRetail(value, record.key, column)}
                />
        );
    }

    handleChangeRetail(value, key, column) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
            target[column] = value;
            this.setState({ retailData: newData });
        }
    }

    newMemberRetailData = () => {
        const newRetailList = [...this.state.retailData];
        const newRecord = {
            key: newRetailList.length + 1,
            nper: '',
            price: '',
            type: 0,
            editable: true,
            isNew: true,
            isPreset: false,
        };
        newRetailList.push(newRecord);
        this.setState({
            retailData: newRetailList
        });
    }

    editRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
            target.editable = true;
            this.setState({ retailData: newData });
        }
    }
    saveRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
            delete target.editable;
            this.setState({ retailData: newData });
            this.cacheDataRetail = newData.map(item => ({ ...item }));
        }
    }
    cancelRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
            Object.assign(target, this.cacheDataRetail.filter(item => key === item.key)[0]);
            delete target.editable;
            this.setState({ retailData: newData });
        }
    }
    deleteRetail(key) {
        const newData = [...this.state.retailData];
        this.setState({ retailData: newData.filter(item => item.key !== key) });
    }

    onStartChange = (value) => {
        this.setState({
            startTime: value,
        });
    }

    onEndChange = (value) => {
        this.setState({
            endTime: value,
        })
        if (value) {
            this.setState({
                selectTimeType: true
            })
        } else {
            this.setState({
                selectTimeType: false
            })
        }
    }

    disabledStartDate = (startTime) => {
        const endTime = this.state.endTime;
        if (!startTime || !endTime) {
            return false;
        }
        return startTime.valueOf() > endTime.valueOf();
    }

    disabledEndDate = (endTime) => {
        const startTime = this.state.startTime;
        if (!endTime || !startTime) {
            return false;
        }
        return endTime.valueOf() <= startTime.valueOf();
    }

    handleStartTimeChange = (date, dateString) => {
        this.setState({
            startTime: dateString,
            selectTimeType: !this.state.selectTimeType,
        });
    }

    handleChangeForeverTime = (e) => {
        this.setState({
            foreverTime: e.target.checked,
            isEndTime: !this.state.isEndTime,
            endTime: ''
        });
    }

    handleStartOpenChange = (open) => {
        if (!open) {
            this.setState({ endOpen: true });
        }
    }

    handleEndOpenChange = (open) => {
        this.setState({ endOpen: open });
    }

    

    render() {
        const { dispatch } = this.props;
        const { isEdit } = this.state;
        const { product: { productDetails, productLoading } } = this.props;
        const { getFieldDecorator, form } = this.props;
        // const title = this.handleJudgeTitls();
        this.onRetailData();

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        const formItemLayout1 = {
            labelCol: {
                span: 11,
            },
            wrapperCol: {
                span: 13,
            },
        };

        return (
            <PageHeaderLayout title="产品新增">
                {/* {JSON.stringify(productDetails)} */}
                <Card bordered={false}>
                    <Form>
                        <FormItem {...formItemLayout} label="产品编号" >
                            {
                                form.getFieldDecorator('productNum', {
                                    initialValue: productDetails && productDetails.productNum,
                                    rules: [{
                                        required: true, message: '请输入产品编号',
                                    }],
                                })(
                                    <Input placeholder="请输入产品编号" />
                                )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品名称" >
                            {
                                form.getFieldDecorator('productName', {
                                    initialValue: productDetails && productDetails.productName,
                                    rules: [{
                                        required: true, message: '请输入产品名称',
                                    }],
                                })(
                                    <Input placeholder="请输入产品名称" />

                                )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="资产种类" >
                            {form.getFieldDecorator('assetType;', {
                                initialValue: productDetails && productDetails.assetType,
                            })(
                                <Select placeholder="请选择资产种类" onChange={this.handleAssetsTypeVariety}>
                                    <Option value={1}>新车</Option>
                                    <Option value={2}>二手车</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品种类" >
                            {form.getFieldDecorator('productType', {
                                initialValue: productDetails && productDetails.productType,
                            })(
                                // <Radio.Group buttonStyle="solid" >
                                //     <Radio.Button value={1}>分期</Radio.Button>
                                //     <Radio.Button value={0}>贷款</Radio.Button>

                                // </Radio.Group>
                                <Select placeholder="请选择产品种类" onChange={this.handleChangeProductVariety}>
                                    <Option value={1}>分期</Option>
                                    <Option value={0}>贷款</Option>
                                </Select>
                            )}
                        </FormItem>
                        {
                            this.state.productVariety == 2 && this.state.type != 1 ?
                                <FormItem {...formItemLayout} label="产品价格" >
                                    {form.getFieldDecorator('productPrice', {
                                        initialValue: productDetails && productDetails.productPrice,
                                    })(
                                        <InputNumber
                                            placeholder="请输入"
                                            style={{ width: '100%' }}
                                            formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                        />
                                    )}
                                </FormItem>
                                :
                                null
                        }
                        {
                            this.state.productVariety == 1 ?
                                <FormItem {...formItemLayout} label="分期费率" >
                                    {form.getFieldDecorator('productPrice', {
                                        initialValue: productDetails && productDetails.productPrice,
                                    })(
                                        <div>
                                            
                                            <Table
                                                rowKey="key"
                                                style={{ marginTop: '15px' }}
                                                dataSource={this.state.retailData}
                                                columns={this.columnsRetail} 
                                                pagination={false}
                                                size="small"
                                                bordered/>
                                                <Button
                                                onClick={this.newMemberRetailData}
                                                style={{ width: '100%' }}
                                                type="primary" icon="plus">
                                                新增
                                            </Button>
                                        </div>
                                    )}
                                </FormItem>
                                :
                                null
                        }
                        
                        <FormItem {...formItemLayout} label="合作银行" >
                            {form.getFieldDecorator('bankName', {
                                initialValue: productDetails && productDetails.bankName,
                            })(
                                <Select placeholder="请选择合作银行">
                                    <Option value={'工商银行'}>工商银行</Option>
                                    <Option value={'农业银行'}>农业银行</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品额度" >
                            {form.getFieldDecorator('productSize', {
                                initialValue: productDetails && productDetails.productSize,
                            })(
                                <InputNumber
                                    placeholder="请输入产品额度"
                                    style={{ width: '100%' }}
                                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品描述" >
                            {form.getFieldDecorator('productDesc', {
                                initialValue: productDetails && productDetails.productDesc,
                            })(
                                <TextArea placeholder="请输入产品描述" rows={4} />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="生效时间" >
                            {form.getFieldDecorator('retail')(

                                <span>
                                    <div>
                                        <DatePicker
                                            disabledDate={this.disabledStartDate}
                                            showTime
                                            format={monthFormat}
                                            placeholder="开始时间"
                                            style={{ width: '45%' }}
                                            onChange={this.onStartChange}
                                            onOpenChange={this.handleStartOpenChange}
                                        />
                                        <DatePicker
                                            disabledDate={this.disabledEndDate}
                                            showTime
                                            style={{ marginLeft: 5 }}
                                            disabled={this.state.isEndTime}
                                            format={monthFormat}
                                            placeholder="结束时间"
                                            style={{ width: '45%', marginLeft: '10px' }}
                                            onChange={this.onEndChange}
                                        // open={this.state.endOpen}
                                        // onOpenChange={this.handleEndOpenChange}
                                        />
                                    </div>
                                    <Checkbox
                                        style={{ marginTop: 10 }}
                                        disabled={this.state.selectTimeType}
                                        onChange={this.handleChangeForeverTime}
                                    >
                                        永久
                                    </Checkbox>
                                </span>
                            )}

                        </FormItem>
                        
                        <FormItem
                            wrapperCol={{
                                xs: { span: 24, offset: 0 },
                                sm: {
                                    span: formItemLayout1.wrapperCol.span,
                                    offset: formItemLayout1.labelCol.span,
                                },
                            }}
                            label=""
                        >
                            <Button type="primary" onClick={this.handleProductAddSubmit} loading={productLoading}>
                                提交
                            </Button>
                        </FormItem>
                    </Form>
                </Card>
            </PageHeaderLayout>
        );
    }
}